import React, { useState } from "react";
import {
  Card,
  Form,
  Input,
  InputNumber,
  Button,
  Space,
  Typography,
  Table,
  Tag,
  Empty,
  Popconfirm,
  message,
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  DeleteOutlined,
  DatabaseOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import { fotaAPI } from "../services/api";

const { Text, Title } = Typography;

const FotaManagement = () => {
  const [queryForm] = Form.useForm();
  const [addForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [adding, setAdding] = useState(false);
  const [currentFota, setCurrentFota] = useState(null);
  const [allDownfiles, setAllDownfiles] = useState([]); // 版本号0返回的全部文件（从msg解析）
  const [fotaList, setFotaList] = useState([]); // 分页列表模式
  const [fotaPagination, setFotaPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 不再使用JSON文本校验，改用可视化表单项（url/file_name）

  const formatDownfilePreview = (downfile) => {
    try {
      const arr = Array.isArray(downfile)
        ? downfile
        : JSON.parse(downfile || "[]");
      return arr.map((f, idx) => ({
        key: idx,
        url: f.url,
        file_name: f.file_name,
      }));
    } catch {
      return [];
    }
  };

  // 从接口返回的 msg 中解析 downfile 数组
  const parseDownfilesFromMsg = (msg) => {
    try {
      const arr = JSON.parse(msg || "[]");
      if (Array.isArray(arr)) {
        return arr.map((f, idx) => ({
          key: idx,
          url: f.url,
          file_name: f.file_name,
        }));
      }
    } catch {}
    return [];
  };

  const parseDownfileString = (downfileStr) => {
    try {
      const arr = JSON.parse(downfileStr || "[]");
      if (Array.isArray(arr)) {
        return arr.map((f, idx) => ({
          key: idx,
          url: f.url,
          file_name: f.file_name,
        }));
      }
    } catch {}
    return [];
  };

  // 查询函数（支持版本0：返回msg内的所有文件）
  const fetchFota = async (version, pageNo = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res = await fotaAPI.getfota({ version, pageNo, pageSize });
      // 若 data 有 list：分页列表渲染
      if (res?.data?.list) {
        setFotaList(res.data.list || []);
        setFotaPagination({
          current: res.data.pageNo || pageNo,
          pageSize: res.data.pageSize || pageSize,
          total: res.data.totalCount || 0,
        });
        setCurrentFota(null);
        setAllDownfiles([]);
      } else if (res?.data) {
        // 单条模式
        setCurrentFota(res.data);
        setAllDownfiles([]);
        setFotaList([]);
        setFotaPagination({ current: 1, pageSize: 10, total: 0 });
      } else {
        const list = parseDownfilesFromMsg(res?.msg);
        setAllDownfiles(list);
        setCurrentFota(null);
        setFotaList([]);
        setFotaPagination({ current: 1, pageSize: 10, total: 0 });
      }
    } finally {
      setLoading(false);
    }
  };

  // 默认初始化：版本号为0，请求“所有数据”
  React.useEffect(() => {
    // 初始化查询表单为 version: 0
    queryForm.setFieldsValue({ version: 0 });
    fetchFota(0);
  }, [queryForm]);

  const handleQuery = async () => {
    try {
      const values = await queryForm.validateFields();
      await fetchFota(values.version, 1, fotaPagination.pageSize || 10);
    } catch (e) {
      // already handled by api
    }
  };

  const handleAdd = async () => {
    try {
      const values = await addForm.validateFields();

      // 将可视化表单的 downfileItems 转为 JSON 字符串
      const items = (values.downfileItems || [])
        .filter((it) => it && (it.url || it.file_name))
        .map((it) => ({
          url: (it.url || "").trim(),
          file_name: (it.file_name || "").trim(),
        }))
        .filter((it) => it.url && it.file_name);

      if (items.length === 0) {
        message.error("请至少添加一条 downfile 记录");
        return;
      }

      const downfile = JSON.stringify(items);
      setAdding(true);
      const res = await fotaAPI.addfota({
        version: values.version,
        bak: values.bak || "",
        downfile,
      });
      message.success("添加成功");
      addForm.resetFields();

      // 添加成功后刷新当前列表/视图
      const version = queryForm.getFieldValue("version") ?? 0;
      await fetchFota(version, fotaPagination.current, fotaPagination.pageSize);
    } catch (e) {
      // api 层或校验已提示
    } finally {
      setAdding(false);
    }
  };

  const handleDelete = async () => {
    if (!currentFota?.id) {
      message.warning("当前没有可删除的记录");
      return;
    }
    try {
      setLoading(true);
      await fotaAPI.delfota(currentFota.id);
      message.success("删除成功");
      setCurrentFota(null);
    } catch (e) {
      // api 层已提示
    } finally {
      setLoading(false);
    }
  };

  const downfileColumns = [
    {
      title: "url",
      dataIndex: "url",
      key: "url",
      render: (v) => <Text copyable>{v}</Text>,
    },
    {
      title: "file_name",
      dataIndex: "file_name",
      key: "file_name",
      render: (v) => <Text code>{v}</Text>,
    },
  ];

  // 列表模式的列定义
  const listColumns = [
    { title: "版本号", dataIndex: "version", key: "version", width: 100 },
    {
      title: "文件数",
      key: "downfileCount",
      width: 100,
      render: (_, record) => parseDownfileString(record.downfile).length,
    },
    {
      title: "备注",
      dataIndex: "bak",
      key: "bak",
      ellipsis: true,
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      width: 180,
      render: (ts) => (ts ? dayjs.unix(ts).format("YYYY-MM-DD HH:mm:ss") : "-"),
    },
    {
      title: "操作",
      key: "action",
      width: 120,
      render: (_, record) => (
        <Popconfirm
          title="确定删除该记录？"
          onConfirm={async () => {
            try {
              setLoading(true);
              await fotaAPI.delfota(record.id);
              message.success("删除成功");
              const version = queryForm.getFieldValue("version") ?? 0;
              await fetchFota(
                version,
                fotaPagination.current,
                fotaPagination.pageSize
              );
            } finally {
              setLoading(false);
            }
          }}
          okText="确定"
          cancelText="取消"
        >
          <Button danger size="small">
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  const handleListTableChange = (pagination) => {
    const version = queryForm.getFieldValue("version") ?? 0;
    fetchFota(version, pagination.current, pagination.pageSize);
  };

  return (
    <Space direction="vertical" size="large" style={{ width: "100%" }}>
      <Card
        title={
          <Space>
            <DatabaseOutlined /> 查询最新版本文件
          </Space>
        }
      >
        {/* 查询功能已隐藏，默认加载版本号为0的数据 */}

        <div style={{ marginTop: 16 }}>
          {fotaList && fotaList.length > 0 ? (
            <Table
              columns={listColumns}
              dataSource={fotaList}
              rowKey="id"
              size="small"
              loading={loading}
              pagination={{
                current: fotaPagination.current,
                pageSize: fotaPagination.pageSize,
                total: fotaPagination.total,
                showSizeChanger: true,
                showTotal: (t) => `共 ${t} 条`,
                pageSizeOptions: ["10", "20", "50", "100"],
              }}
              onChange={handleListTableChange}
              expandable={{
                expandedRowRender: (record) => (
                  <Table
                    columns={downfileColumns}
                    dataSource={parseDownfileString(record.downfile)}
                    size="small"
                    pagination={false}
                    rowKey="key"
                  />
                ),
              }}
            />
          ) : currentFota ? (
            <Space direction="vertical" style={{ width: "100%" }}>
              <Space wrap>
                <Tag color="blue">ID: {currentFota.id}</Tag>
                <Tag color="green">版本: {currentFota.version}</Tag>
                <Tag color="geekblue">
                  创建时间:{" "}
                  {currentFota.createdAt
                    ? dayjs
                        .unix(currentFota.createdAt)
                        .format("YYYY-MM-DD HH:mm:ss")
                    : "-"}
                </Tag>
                {currentFota.bak ? (
                  <Tag color="purple">备注: {currentFota.bak}</Tag>
                ) : null}
              </Space>
              <Table
                columns={downfileColumns}
                dataSource={formatDownfilePreview(currentFota.downfile)}
                size="small"
                pagination={{ pageSize: 5, showSizeChanger: true }}
                rowKey="key"
              />
              <div>
                <Popconfirm
                  title="确定删除当前FOTA记录？"
                  onConfirm={handleDelete}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button danger icon={<DeleteOutlined />} loading={loading}>
                    删除当前记录
                  </Button>
                </Popconfirm>
              </div>
            </Space>
          ) : allDownfiles.length > 0 ? (
            <Space direction="vertical" style={{ width: "100%" }}>
              <Space wrap>
                <Tag color="blue">全部文件</Tag>
              </Space>
              <Table
                columns={downfileColumns}
                dataSource={allDownfiles}
                size="small"
                pagination={{ pageSize: 10, showSizeChanger: true }}
                rowKey="key"
              />
            </Space>
          ) : (
            <Empty description="暂无数据" />
          )}
        </div>
      </Card>

      <Card
        title={
          <Space>
            <DatabaseOutlined /> 添加FOTA文件
          </Space>
        }
      >
        <Form
          layout="vertical"
          form={addForm}
          initialValues={{ downfileItems: [{ url: "", file_name: "" }] }}
        >
          <Form.Item
            name="version"
            label="版本号"
            rules={[
              { required: true, message: "请输入版本号" },
              {
                validator: (_, value) => {
                  if (typeof value === "number" && value > 0)
                    return Promise.resolve();
                  return Promise.reject(new Error("版本号必须大于0"));
                },
              },
            ]}
          >
            <InputNumber min={1} precision={0} style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="bak" label="备注">
            <Input placeholder="可选" />
          </Form.Item>

          {/* 可视化 downfile 编辑 */}
          <Form.List name="downfileItems">
            {(fields, { add, remove }) => (
              <div>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    marginBottom: 8,
                  }}
                >
                  <Text strong>downfile 列表</Text>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    icon={<PlusOutlined />}
                  >
                    添加一行
                  </Button>
                </div>
                {fields.length === 0 ? (
                  <Empty description="暂无downfile项，请点击上方按钮添加" />
                ) : (
                  fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      align="baseline"
                      style={{ display: "flex", marginBottom: 8 }}
                    >
                      <Form.Item
                        {...restField}
                        name={[name, "url"]}
                        rules={[{ required: true, message: "请输入url" }]}
                      >
                        <Input
                          placeholder="url，如：http://www.example.com/app.py"
                          style={{ width: 360 }}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, "file_name"]}
                        rules={[{ required: true, message: "请输入文件路径" }]}
                      >
                        <Input
                          placeholder="file_name，如：/usr/app.py"
                          style={{ width: 260 }}
                        />
                      </Form.Item>
                      <Button danger onClick={() => remove(name)}>
                        删除
                      </Button>
                    </Space>
                  ))
                )}
              </div>
            )}
          </Form.List>

          <Form.Item>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
              loading={adding}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </Space>
  );
};

export default FotaManagement;
